/**
  ETFAna project, Anyang Normal University && IMP-CAS
  \class ETFTask
  \brief abstract base class for generic tasks in ETFAna
  \author SUN Yazhou, asia.rabbit@163.com
  \since 2023-07-01
  \date 2024-06-19 last modified
  \attention
  changelog
  <table>
  <tr>  <th>Date         <th>Author      <th>Description                   </tr>
  <tr>  <td>2023-07-01   <td>Asia Sun    <td>file created                  </tr>
  </table>

  \copyright Copyright (c) 2021-2024 Anyang Normal U. && IMP-CAS with LGPLv3 LICENSE
*/

#include <TFile.h>
#include <TH1.h>
#include <TDirectory.h>

#include "ETFRun.h"
#include "ETFTask.h"
#include "ETFPXISection.h"
#include "ETFVMEEvent.h"
#include "ETFParaManager.h"
#include "ETFHistManager.h"
#include "ETFDetectorManager.h"
#include "ETFTrackManager.h"
#include "ETFPIDManager.h"
#include "ETFAnalyzer.h"
#include "ETFMsg.h"

ETFTask::ETFTask(const char *name) : fName(name), fAnaLevel(0), fFolder(0),
fTree(0), fRootFile(0), fSrc(0), fRun(0), fpm(0){}

ETFTask::~ETFTask(){
  if(fFolder){ delete fFolder; fFolder = nullptr; }
} // end dtor

void ETFTask::Init(){
  fRun = ETFRun::Instance();
  fpm = ETFParaManager::Instance();
  fhm = ETFHistManager::Instance();
  fdm = ETFDetectorManager::Instance();
  fAnalyzer = fRun->GetAnalyzer();
  fAnaLevel = fAnalyzer->AnaLevel();
  if(fAnaLevel >= 1) ftm = ETFTrackManager::Instance();
  if(fAnaLevel >= 2){
    fpidm = ETFPIDManager::Instance();
    fPID = fpidm->GetPID();
    fPIDm = fpidm->GetPIDm();
  } // end if
  fRootFile = fRun->GetRootFile();
  fTree = fRun->GetTree();
  fSrc = fRun->GetSource();
  fPXISections = fAnalyzer->GetPXISections();
  fVMEEvents = fAnalyzer->GetVMEEvents();

  CreateHistos();
} // end member function Init

void ETFTask::WriteHistos(){
  fRootFile->cd();
  if(fFolder) fFolder->Write("", TObject::kOverwrite);
} // end member function WriteHistos

// subdir -> TaskName/subdir
void ETFTask::addh(TH1 *h, const string &subdir){
  if("" == subdir) fFolder->Add(h);
  else{
    TDirectory *ff = (TDirectory *)fFolder->FindObject(subdir.data());
    if(!ff) ff = fFolder->mkdir(subdir.data());
    ff->Add(h);
  } // end else
  fhm->AddHist(h->GetName(), h);
} // end member function addh
